<template>
  <div id="roles">
    <el-row class="table-grid-content">
      <el-col :span="6">
        <el-input v-model="input" placeholder="请输入关键字"></el-input>
      </el-col>
      <el-col :span="2" :offset="1">
        <el-button type="primary" icon="el-icon-plus" @click="addUsers()">增加角色</el-button>
      </el-col>
      <el-col :span="2" :offset="1">
        <el-button type="danger" icon="el-icon-delete" @click="batchDelUsers()">删除</el-button>
      </el-col>
      <el-col :span="2" style="margin-left: 14px;">
        <el-button @click="toggleSelection()" icon="el-icon-link">取消</el-button>
      </el-col>
    </el-row>
    <!-- 表格-->
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
      :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="uid" label="用户id" width="150">
      </el-table-column>
      <el-table-column prop="uName" label="用户id" width="150">
      </el-table-column>
      <el-table-column prop="uPwd" label="用户密码" width="160"></el-table-column>
      <el-table-column prop="resperson" label="角色编号" width="160"></el-table-column>
      <!-- <el-table-column prop="statics" label="状态" width="160"></el-table-column> -->
      <el-table-column label="状态" width="160">
        <template slot-scope="scope">
          <el-switch @change="switchs(scope.row)" v-model="scope.row.statics" active-color="#13ce66"
            inactive-color="#ff4949" active-value="开启" inactive-value="禁用">
          </el-switch>
        </template>
      </el-table-column>
      </el-tooltip>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)" round>修改</el-button>
          <!-- <el-button type="primary" plain>主要按钮</el-button> -->
          <el-button size="mini" type="info" @click="handleDelete(scope.row.uid)" round>设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页-->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
        :page-sizes="[4,5,7]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 增加-->
    <el-dialog title="增加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="用户名称" :label-width="formLabelWidth">
          <el-input v-model="form.uName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.uPwd" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="路径" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="form.statics" placeholder="请选择">
            <el-option label="开启" value="开启"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改-->
    <el-dialog title="修改角色" :visible.sync="dialogUpdaVisible">
      <el-form :model="form">
        <el-form-item label="编号" :label-width="formLabelWidth">
          {{form.uid}}
        </el-form-item>
        <el-form-item label="用户名称" :label-width="formLabelWidth">
          <el-input v-model="form.uName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth">
          <el-input v-model="form.uPwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="负责人编号" :label-width="formLabelWidth">
          <el-input v-model="form.snum" autocomplete="off" disabled=""></el-input>
        </el-form-item>
        <el-form-item label="用户状态" :label-width="formLabelWidth">
          <el-select v-model="form.statics" placeholder="请选择">
            <el-option label="开启" value="开启"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdaVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 赋权-->
    <el-drawer title="角色赋权" :before-close="handleClose" :visible.sync="dialog" direction="rtl"
      custom-class="demo-drawer" ref="drawer">
      <div class="demo-drawer__content">
        <el-tree :data="data.roles" show-checkbox node-key="rid"
         :default-checked-keys="data.userRids" :props="defaultProps" ref="tree">
        </el-tree>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm" round>取 消</el-button>
          <el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading" round>
            {{ loading ? '提交中 ...' : '确 定' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  export default {
    name: 'users',
    data() {
      return {
        uid:0,
        input: '',
        input2: '',
        pageNum: 1,
        pageSize: 7,
        total: 0,
        dialogFormVisible: false,
        dialogUpdaVisible: false,
        dialogRolesVisible: false,
        formLabelWidth: '90px',
        tableData: [],
        multipleSelection: [],
        form: {
          uid: 0,
          uName: '',
          uPwd: '',
          snum: '',
          statics: ''
        },

        table: false,
        dialog: false,
        loading: false,
        formLabelWidths: '80px',
        timer: null,
        data: [],
        defaultProps: {
          children: 'children',
          label: 'rname'
        }
      }
    },
    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
          this.multipleSelection = [];

        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = [];
        for (var i = 0; i < val.length; i++) {
          this.multipleSelection.push(val[i].uid)
        }
      },
      tableRowClassName({
        row,
        rowIndex
      }) {
        if (rowIndex % 2 == 0) {
          return 'success-row';
        } else {
          return 'warning-row';
        }
        return '';
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.searchUsers(this.pageNum, this.pageSize);
      },
      handleCurrentChange(val) {
        this.pageNum = val;
        this.searchUsers(this.pageNum, this.pageSize);
      },
      addUsers() {
        this.dialogFormVisible = true;
      },
      /* 修改*/
      handleEdit(data) {
        this.form.uid = data.uid;
        this.form.uName = data.uName
        this.form.uPwd = data.uPwd;
        this.form.statics = data.statics;
        this.form.snum = data.snum;
        this.dialogUpdaVisible = true;
      },
      handleClose(done) {
        if (this.loading) {
          return;
        }
        this.$confirm('确定要提交表单吗？')
          .then(_ => {
            this.loading = true;
            this.timer = setTimeout(() => {
              done();
              // 动画关闭需要一定的时间
              var rad = ''
              var ridsa = this.$refs.tree.getCheckedKeys().join(',') // 获取当前的选中的数据[数组] -id, 把数组转换成字符串
              var ridsb = this.$refs.tree.getCheckedNodes() // 获取当前的选中的数据{对象}
              ridsb.forEach(ids => { //获取选中的所有的父级id
                if (ids.pid != null) {
                  rad += ',' + ids.pid
                }
              })
              rad = rad.substr(1) // 删除字符串前面的','
              var rids = ridsa
              var arr = rids.split(',') //  把字符串转换成数组
              arr = [...new Set(arr)]; // 数组去重
              rids = arr.join(',') // 把数组转换成字符串
              var data = new URLSearchParams();
              data.append("rid", rids);
              data.append("uid", this.uid);
              this.$http.post('system/user/setUserRole', data).then(res => {
                if (res.state = 200) {
                  console.log("设置成功")
                  // var id = this.user.rid;
                  // if (this.rid == id) {
                  //   this.reload();
                  //   this.$router.push('/main/menus');
                  // }
                }
              }).catch(err => {
                console.log(err);
              })



              setTimeout(() => {
                this.loading = false;
              }, 100);
            }, 500);
          })
          .catch(_ => {});
      },
      cancelForm() {
        this.loading = false;
        this.dialog = false;
        clearTimeout(this.timer);
      },
      handleDelete(uid) {
        this.uid =uid;
        this.$http.post('system/role/roleDto?uid='+uid).then(res=>{
              if(res.data.roles.length!=0){
                this.data=res.data;
              }
        }).catch(err=>{
          console.log(err)
        })



        this.dialog = true;

      },
      searchUsers(pageNum, pageSize) {
        var data = new URLSearchParams();
        data.append("pageNum", pageNum);
        data.append("pageSize", pageSize);
        this.$http.post('system/user/findByPager', data).then(res => {
          this.tableData = res.data.rows;
          this.pageNum = res.data.pageNum;
          this.pageSize = res.data.pageSize;
          this.total = res.data.total;
        }).catch(err => {
          console.log(err);
        })
      },
      saveUser() {
        this.dialogFormVisible = false;

        var data = new URLSearchParams();
        /* uName: '',
          uPwd: '',
          snum: '',
          statics: ''*/
        data.append("uName", this.form.uName);
        data.append("uPwd", this.form.uPwd);
        data.append("statics", this.form.statics);
        this.$http.post("system/user/addUser", data).then(res => {

          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.searchUsers(this.pageNum, this.pageSize);
          this.form.uid = '';
          this.form.uName = '';
          this.form.uPwd = '';
          this.form.statics = '';
          this.form.snum = '';

        }).catch(err => {
          console.log(err);
        })
      },
      batchDelUsers() {
        var uids = this.multipleSelection;
        if (uids.length > 0) {
          if (confirm('确定删除?')) {
            var data = new URLSearchParams();
            data.append("uids", uids);
            this.$http.post('system/user/batchDelUser', data).then(res => {
              if (res.state = 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.searchUsers(this.pageNum, this.pageSize);
              }
            }).catch(err => {
              console.log(err);
            })
          }
        } else {
          alert('请选择要删除的信息');
        }
      },
      updateUser() {
        this.dialogUpdaVisible = false;
        var data = new URLSearchParams();
        data.append("uName", this.form.uName);
        data.append("uPwd", this.form.uPwd);
        data.append("statics", this.form.statics);
        data.append("uid", this.form.uid);
        this.$http.post('system/user/updateUser', data).then(res => {

          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.searchUsers(this.pageNum, this.pageSize);
          this.form.uid = '';
          this.form.uName = '';
          this.form.uPwd = '';
          this.form.statics = '';
          this.form.snum = '';

        }).catch(err => {

        })

      },
      switchs(data) {
        console.log('id :' + data.uid);
        console.log('数据: ' + data.statics);
        this.$http.post('system/user/updateStatics', this.$qs.stringify(data)).then(res => {
             this.searchUsers(this.pageNum, this.pageSize);
        }).catch(err => {
          console.log(err);
        })
      }
    },
    mounted() {
      this.searchUsers(this.pageNum, this.pageSize);

    }
  }
</script>

<style>
  .el-input {
    width: 85%;
  }

  .block {
    margin-top: 8px;
  }

  .el-pagination {
    text-align: center;
  }

  .el-table .warning-row {
    background: white;
  }

  .el-table .success-row {
    background: whitesmoke;
  }

  #roles {
    line-height: 0px;

    margin-top: 2sspx;
    padding: 13px;
  }

  .el-table {

    margin-top: 10px;
  }

  .el-tree {
    padding-left: 10px;
    background: whitesmoke;
  }

  .demo-drawer__footer {
    margin-left: 20px;
    margin-top: 15px;
  }
</style>
